<template>
<div id="scrollList">
  <div class="loader-base" v-if="showLoad"><div class="loader-wrap"></div></div>
  <header class="hd-top">
    <span class="iconfont icon-left" @click="goBack"></span>
    <h2 class="title">{{type=='1'?'待提货':'待交货'}}</h2>
  </header>
  <div class="displayflex top-bar-w">
    <div class="top-bar-c flex1">
      <i class="iconfont icon-sech"></i> 
      <div class="ipt"><input type="text" placeholder="输入订单号" v-model="bbillno"></div>
    </div> 
    <div class="btn-sech" @click="resetGet()">搜索</div>
  </div>
  <scroller lock-x height="-52" @on-scroll-bottom="onScrollBottom" ref="scrollerBottom" :scroll-bottom-offst="100" v-show="todolist.length>0">
  <div>
    <div class="list-warp" v-for="item in todolist">
      <div class="list-ctx" @click="goDetail(item.BBillGuid)">
        <div class="head cf ft14">
          <p class="f-l">{{item.BBillNo}}</p>
          <span class="tag f-l" v-if="item.StartBusTerminal">中转</span>
          <span class="f-r">{{type=='1'?'待提货':'待交货'}}</span>
        </div>
        <div class="grab-wrap">
          <div class="addr ft17"><span class="dotted"></span>{{item.DepartureProvince | province}}{{item.DepartureCity | city}}{{item.DepartureDistrict | district}}{{item.DepartureAddress}}</div>
          <div class="addr ft17" v-if="item.StartBusTerminal"><span class="iconfont icon-trans"></span>{{item.StartBusTerminal.replace(/\//g, "")}}</div>
          <div class="addr ft17"><span class="dotted org"></span>{{item.ArrivalProvince | province}}{{item.ArrivalCity | city}}{{item.ArrivalDistrict | district}}{{item.ArrivalAddress}}</div>
          <div class="statis ft14 displayflex">
            <span>{{item.OrdersVolumn}}m³，{{item.OrdersWeight}}kg，共{{item.OrdersPKGS}}件</span>
            <div class="flex1 txt-rit">订单总费用<em class="org">￥</em><span class="price org ft16">{{item.DistributionIncome + item.BusTicketAmount}}</span></div>
          </div>
          <div class="ft14" v-if="item.BusTerminal">客运站：<span class="org">{{item.BusTerminal | noslash}}</span></div>
          <div class="ft14" v-if="type==1">最晚提货时间：<span class="org">{{item.CollectionTime | ydmhm}}</span></div>
          <div class="ft14">要求到达时间：<span class="org">{{item.LastArrivalArrivedDate | ydmhm}}</span></div>
          
          <template v-if="type==1">
            <div class="ft14">距离最晚提货时间仅剩：<span class="org">{{item.CollectionTime | DateTransformation}}</span></div>
          </template>
          
          <template v-if="type==2">
            <div class="ft14">距离截至时间仅剩：<span class="red">{{item.LastArrivalArrivedDate | DateTransformation}}</span></div>
          </template>
        </div>
        <div class="icon-tag" v-if="item.BBillType == 'B05'"><img src="~images/icon/emergent.png"></div>
      </div>
      <div class="list-btn">
        <div class="btn btn-sm" @click="goDetail(item.BBillGuid)">订单详情</div>
        <div class="btn btn-sm" v-if="type=='1'" @click="goLink(item.BBillGuid)">拍照取货</div>
        <div class="btn btn-sm" v-if="type=='1' && item.ConsignTime == null" @click="ConfirmArrival(item.DepartureVenue,item.DepartureAddress,item.Guid)">确认到达</div>
        <div class="btn btn-sm" v-if="type=='2'" @click="goLink(item.BBillGuid)">交货确认</div>
      </div>
    </div>
  </div>
  <p class="txt-bottom" v-if="totalLength == todolist.length && totalLength>3"><em class="txt">我是有底线的</em></p>
  </scroller>
  <div class="noDate_page" v-if="todolist.length<=0">
    <div class="noDate_icon"><i class="iconfont icon-null"></i></div>
    未找到相关数据
  </div>
  
  <div id="mapcontainer" style="display:none; width:0px; height:0px"></div>
</div>
</template>

<script>
export default {
  data() {
    return {
      todolist: [],
      showLoad: false,
      State: "",
      bbillno: "",
      count: 0,
      pageindex: 1,
      totalLength: 0,
      fullText: "",
      DepartureVenue: "",
      DepartureAddress: ""
    };
  },
  computed: {
    type() {
      var val = this.$route.query.type;
      return val.toString();
    },
    userinfo() {
      if (localStorage.UserInfo) {
        return JSON.parse(localStorage.UserInfo);
      }
    }
  },
  created() {
    this.getData();
    var title = "";
    switch (this.type) {
      case "1":
        title = "待提货";
        break;
      case "2":
        title = "在途";
        break;
    }
    document.title = title;
  },
  watch: {
    bbillno(val) {
      if (!val) {
        this.resetGet();
      }
    }
  },
  methods: {
    goBack() {
      this.$router.go(-1);
    },
    goLink(id) {
      this.$router.push({
        path: "/pickUp",
        query: {
          id: id,
          step: this.type
        }
      });
    },
    goDetail(id) {
      this.$router.push({
        path: "/orderDetail",
        query: { id: id }
      });
    },
    resetGet() {
      this.todolist = [];
      this.count = 0;
      this.pageindex = 1;
      this.getData();
    },
    onScrollBottom() {
      this.count++;
      if (this.count == 1) {
        this.getData();
        this.$nextTick(() => {
          this.$refs.scrollerBottom.reset();
        });
      }
    },
    getData() {
      var _this = this;
      if (this.type == 1) {
        _this.State = 51;
      } else {
        _this.State = 52;
      }
      var query = {
        BBillNo: _this.bbillno,
        DriverGuid: this.userinfo.StaffID,
        State: _this.State,
        PageIndex: this.pageindex,
        PageSize: 8
      };
      _this.showLoad = true;

      _this.Ajax.post("SearchTakableOrderList", query).then(function(resp) {
        _this.showLoad = false;
        if (resp.IsSuccess) {
          var result = resp.Datas;
          if (result.length > 0) {
            _this.todolist = _this.todolist.concat(result);
            _this.pageindex++;
            _this.count = 0;
          }
          _this.totalLength = resp.TotalRecords;
        }
      });
    },
    getMapDistance(origin, destinat, Guid) {
      var self = this;
      var query = {
        origin: origin,
        destinat: destinat,
        Guid: Guid
      };
      this.Ajax.post("GetMapDistanceDD", query).then(function(resp) {
        if (resp.IsSuccess) {
          var DistanceMeter = resp.Data.DistanceMeter;
          if (DistanceMeter > 500) {
            self.$vux.toast.show({
              type: "text",
              width: "auto",
              text: "距离取货地点大于500米，无法确认到达。"
            });
          } else {
            self.$vux.toast.show({
              type: "text",
              width: "auto",
              text: "已到达取货地"
            });
            location.reload();
          }
        }
      });
    },
    ConfirmArrival(DepartureVenue, DepartureAddress, Guid) {
      this.getCurrent(DepartureVenue, DepartureAddress, Guid);
    },
    getCurrent(DepartureVenue, DepartureAddress, Guid) {
      this.showLoad = true;
      var map = new AMap.Map("mapcontainer", {});
      var _this = this;
      var geolocation = null;
      map.plugin("AMap.Geolocation", function() {
        geolocation = new AMap.Geolocation({
          enableHighAccuracy: true, //是否使用高精度定位，默认:true
          timeout: 10000, //超过10秒后停止定位，默认：无穷大
          maximumAge: 0, //定位结果缓存0毫秒，默认：0
          convert: true, //自动偏移坐标，偏移后的坐标为高德坐标，默认：true
          showButton: true, //显示定位按钮，默认：true
          buttonPosition: "LB", //定位按钮停靠位置，默认：'LB'，左下角
          buttonOffset: new AMap.Pixel(10, 20), //定位按钮与设置的停靠位置的偏移量，默认：Pixel(10, 20)
          showMarker: true, //定位成功后在定位到的位置显示点标记，默认：true
          showCircle: true, //定位成功后用圆圈表示定位精度范围，默认：true
          panToLocation: true, //定位成功后将定位到的位置作为地图中心点，默认：true
          zoomToAccuracy: true //定位成功后调整地图视野范围使定位位置及精度范围视野内可见，默认：false
        });
        // ios环境切换到使用远程https定位
        if (AMap.UA.ios) {
          //使用远程定位，见 remogeo.js
          var remoGeo = new RemoGeoLocation();
          //替换方法
          navigator.geolocation.getCurrentPosition = function() {
            return remoGeo.getCurrentPosition.apply(remoGeo, arguments);
          };
          //替换方法
          navigator.geolocation.watchPosition = function() {
            return remoGeo.watchPosition.apply(remoGeo, arguments);
          };
        }

        map.addControl(geolocation);
        geolocation.getCurrentPosition();
        AMap.event.addListener(geolocation, "complete", onComplete); //返回定位信息
        AMap.event.addListener(geolocation, "error", onError); //返回定位出错信息
      });
      /*
       *解析定位结果
       */
      function onComplete(data) {
        _this.showLoad = false;
        var str = "定位成功:";
        str += "经度：" + data.position.getLng();
        str += "纬度：" + data.position.getLat();
        str += "精度：" + data.accuracy + " 米";
        str += "是否经过偏移：" + (data.isConverted ? "是" : "否");
        //var provinceTxt = _this.province(data.addressComponent.province), cityTxt = _this.city(data.addressComponent.city), districtTxt = _this.district(data.addressComponent.district);
        var fullText =
          data.addressComponent.province +
          data.addressComponent.city +
          data.addressComponent.district;
        _this.fullText = fullText + data.formattedAddress.replace(fullText, "");
        var destinat = DepartureVenue.replace(/\//g, "") + DepartureAddress;
        _this.getMapDistance(_this.fullText, destinat, Guid);
      }
      /*
       *解析定位错误信息
       */
      function onError(data) {
        _this.showLoad = false;
        var str = "定位失败";
        str += "错误信息：";
        switch (data.info) {
          case "POSITION_UNAVAILBLE":
            str += "无法获得当前位置";
            break;
          case "PERMISSION_DENIED":
            str += "浏览器阻止了定位操作";
            break;
          case "TIMEOUT":
            str += "定位超时";
            break;
          default:
            str += "未知错误";
            break;
        }
        _this.$vux.toast.show({
          type: "text",
          width: "auto",
          text: str
        });
      }
    }
  }
};
</script>